package manager

import (
	"github.com/tianjigames/fairy/constants"
	"github.com/tianjigames/fairy/model"
	"github.com/tianjigames/fairy/template"
	"github.com/topfreegames/pitaya"
	"strconv"
	"sync"
)

var (
	TitleManager *titleManager
	titleManagerOnce sync.Once
)

/**
称号管理器
 */
type titleManager struct {
	BaseManager
}

func NewTitleManager() *titleManager {
	titleManagerOnce.Do(func() {
		TitleManager = &titleManager{

		}
	})

	return TitleManager
}

/**
计算称号对某个属性加成值
 */
func (p *titleManager) CalTitleAttr(player *model.PlayerObject,attrId *constants.AttrFlag) int {
	if player == nil || attrId == nil {
		return 0
	}

	nAttr := 0
	titleId := player.PlayerData.TitleId
	v := pitaya.GetTemplateById(template.TitleDefineKey,strconv.FormatInt(int64(titleId),10))
	if v != nil {
		nAttr += p.CalTitleAttrValue(player,v.(*template.TitleDefine),attrId,true)
	}

	titleIdStr := strconv.FormatInt(int64(titleId),10)
	titleIdList := player.MTitleData.TitleList
	for i := 0;i< constants.MaxTitleNum;i++ {
		if titleIdList[i] <= 0 {
			continue
		}

		v = pitaya.GetTemplateById(template.TitleDefineKey,strconv.FormatInt(int64(titleIdList[i]),10))
		if v == nil {
			continue
		}

		titleCfgTemp := v.(*template.TitleDefine)
		if titleCfgTemp.Id == titleIdStr {
			continue
		}

		nAttr += p.CalTitleAttrValue(player,titleCfgTemp,attrId,false)
	}
	return nAttr
}

/**
计算称号的加成属性值
 */
func (p *titleManager) CalTitleAttrValue(player *model.PlayerObject,title *template.TitleDefine,
	attrId *constants.AttrFlag,positive bool) int {
	if player == nil || title == nil || attrId == nil {
		return 0
	}

	var k,count int
	if positive {//激活的称号
		k = 1
		count = constants.TitlePositiveAttr
	}else {//未激活的称号
		k = 1 + constants.TitlePositiveAttr
		count = constants.TitlePositiveAttr + constants.TitlePassitiveAttr
	}

	nRet := 0
	nBaseValue := player.GetBaseAttr(attrId)
	rt := model.RefixTypeVTValue
	for ;k <= count;k++ {
		pro := p.GetTitleAttrConfig(title,k)
		if pro == nil || len(pro) < constants.TitleIdxAttrLen {
			continue
		}

		if pro[0] == int(*attrId) {
			nRet += LoadPlayerInfoManager.GetAttrResult(&rt,pro[1],nBaseValue)
		}else {
			nRet += LoadPlayerInfoManager.CheckSpecialAttrByFlag(attrId,constants.GetAttrFlagByValue(pro[0]),
				&rt,pro[1],nBaseValue)
		}
	}

	return nRet
}

/**
获取称号加成数组
 */
func (p *titleManager) GetTitleAttrConfig(title *template.TitleDefine,nIdx int) []int {
	if nIdx <= 0 || nIdx > constants.TitlePositiveAttr + constants.TitlePassitiveAttr {
		return nil
	}

	switch nIdx {
	case 1:
		return title.PositiveAttr1
	case 2:
		return title.PositiveAttr2
	case 3:
		return title.PassiveAttr1
	case 4:
		return title.PassiveAttr2
	}
	return nil
}






















